package cn.com.acca.ma.service.impl;

import cn.com.acca.ma.common.util.PropertiesUtil;
import cn.com.acca.ma.model.StockTransactionData;
import cn.com.acca.ma.model.StockTransactionDataAll;
import cn.com.acca.ma.service.PrintStockService;
import lombok.extern.slf4j.Slf4j;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;

import java.awt.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PrintStockServiceImpl extends BaseServiceImpl<PrintStockServiceImpl, Object> implements PrintStockService {

    /**
     * 打印波段操作的股票，并发送邮件
     */
    @Override
    public void printStockInBullAndSendMail() {
        String date = PropertiesUtil.getValue(PRINT_PROPERTIES, "print.stock.inBull.date");
        // 发邮件的参数
        String mailHost = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.host");
        String mailTransportProtocol = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.transport.protocol");
        String mailSmtpAuth = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.smtp.auth");
        String mailUsername = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.username");
        String mailPassword = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.password");
        String mailSubject = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.bondOperationStock.subjectInBull");
        stockTransactionDataDao.findStockInBullAndSendMail(date, mailHost, mailTransportProtocol, mailSmtpAuth, mailUsername, mailPassword, mailSubject);
    }

    /**
     * 打印波段操作的股票（熊市），并发送邮件
     */
    @Override
    public void printStockInShortAndSendMail() {
        String date = PropertiesUtil.getValue(PRINT_PROPERTIES, "print.stock.inShort.date");
        // 发邮件的参数
        String mailHost = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.host");
        String mailTransportProtocol = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.transport.protocol");
        String mailSmtpAuth = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.smtp.auth");
        String mailUsername = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.username");
        String mailPassword = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.password");
        String mailSubject = PropertiesUtil.getValue(PROJECT_PROPERTIES, "mail.bondOperationStock.subjectInShort");
        stockTransactionDataDao.findStockInShortAndSendMail(date, mailHost, mailTransportProtocol, mailSmtpAuth, mailUsername, mailPassword, mailSubject);
    }

    /**
     * 创建符合波段操作条件的股票的百分比图
     */
    @Override
    public void createBondOperationPercentagePicture() {
        String beginDate = PropertiesUtil.getValue(STOCK_RECORD_PICTURE_PROPERTIES, "stockRecordPicture.bondOperation.beginDate");
        String endDate = PropertiesUtil.getValue(STOCK_RECORD_PICTURE_PROPERTIES, "stockRecordPicture.bondOperation.endDate");

        // 符合条件的数量的列表
        List<Double> numberList = new ArrayList<>();
        // 日期列表
        List<String> dateList = stockTransactionDataDao.findDistinctDateBetweenBeginDateAndEndDate(false, beginDate, endDate);
        for (String date : dateList) {
            List<String> codeList = stockTransactionDataDao.findStockInBull(date);
            List<StockTransactionData> stockTransactionDataAllList = stockTransactionDataDao.findByDate(date);
            double codeListSize = Double.valueOf(codeList.size());
            double stockTransactionDataAllListSize = Double.valueOf(stockTransactionDataAllList.size());
            numberList.add(Double.valueOf(codeListSize / stockTransactionDataAllListSize *100));
//            numberList.add(Double.valueOf(codeListSize));
        }

        JFreeChart jfreechart;

        TimeSeries bondOperationSeries = new TimeSeries("符合波段操作条件的股票数量的百分比", org.jfree.data.time.Day.class);
        TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();

        for (int i = 0; i < dateList.size(); i++) {
            String[] str = dateList.get(i).toString().split("-");
            int year = Integer.parseInt(str[0]);
            int month = Integer.parseInt(str[1]);
            int day = Integer.parseInt(str[2]);
            Double number = numberList.get(i);
            bondOperationSeries.add(new Day(day, month, year), number.doubleValue());
        }

        timeSeriesCollection.addSeries(bondOperationSeries);

        // 配置字体
        // X轴字体
        Font xFont = new Font("宋体", Font.PLAIN, 40);
        // Y轴字体
        Font yFont = new Font("宋体", Font.PLAIN, 40);
        // 底部字体
        Font bottomFont = new Font("宋体", Font.PLAIN, 40);
        // 图片标题字体
        Font titleFont = new Font("隶书", Font.BOLD, 50);

        jfreechart = ChartFactory.createTimeSeriesChart("符合波段操作条件的股票数量的百分比",
                "日期", "百分比", timeSeriesCollection, true, true, true);

        jfreechart.setBackgroundPaint(Color.white);
        // 图片标题
        jfreechart.setTitle(new TextTitle(jfreechart.getTitle().getText(), titleFont));
        // 底部字体
        jfreechart.getLegend().setItemFont(bottomFont);

        XYPlot xyPlot = (XYPlot) jfreechart.getPlot();
        xyPlot.setBackgroundPaint(Color.lightGray);
        xyPlot.setDomainGridlinePaint(Color.white);
        xyPlot.setRangeGridlinePaint(Color.white);
        xyPlot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
        xyPlot.setDomainCrosshairVisible(true);
        xyPlot.setRangeCrosshairVisible(true);

        // X轴
        ValueAxis domainAxis = xyPlot.getDomainAxis();
        // X轴标题字体
        domainAxis.setLabelFont(xFont);
        // Y轴
        ValueAxis rangeAxis = xyPlot.getRangeAxis();
        // Y轴标题字体
        rangeAxis.setLabelFont(yFont);

        org.jfree.chart.renderer.xy.XYItemRenderer xyItemRenderer = xyPlot.getRenderer();
        // 设置所有线条粗细
        xyItemRenderer.setStroke(new BasicStroke(5.0F));
        if (xyItemRenderer instanceof XYLineAndShapeRenderer) {
            XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyItemRenderer;
            xylineandshaperenderer.setBaseShapesVisible(true);
            xylineandshaperenderer.setBaseShapesFilled(true);
        }

        DateAxis dateaxis = (DateAxis) xyPlot.getDomainAxis();
        dateaxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));

        try {
            FileOutputStream fos = new FileOutputStream(PICTURE_PATH + "bond_operation_stock_percentage/" + beginDate + "-" + endDate + PICTURE_FORMAT);
            // 将统计图标输出成JPG文件
            ChartUtilities.writeChartAsJPEG(fos, // 输出到哪个输出流
                    1, // JPEG图片的质量，0~1之间
                    jfreechart, // 统计图标对象
                    imageWidth, // 宽
                    IMAGE_HEIGHT, // 高
                    null // ChartRenderingInfo 信息
            );
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String listToString(List list) {
        return null;
    }
}
